<?php if ( ! defined('APPPATH')) exilang('No direct script access allowed');
/**
 *      [PinTuXiu] (C)2001-2099 ONightjar.com Pintuxiu.com.
 *      This is NOT a freeware, use is subject to license terms
*/

class home_controller extends PZ_Controller{

	public function __construct() {
		parent::__construct();
		$this->authfunctions = array('focus','basicsetting','securitysetting','bindforum','bindsetting','starsetting',
				'storesetting','atshare','createalbum','albumupdate','createtopic','updatetopic','creategroup','updategroup','groups',
				'starsetting','storesetting','store','message','sendmessage','alert');
	}

	protected function init(){
		$this->page = $this->param('page','1');
		$this->sname =  $this->param("sname");
		$userapi = load_api('user');
		if(in_array($this->method , $this->authfunctions)){
			$this->uid = $this->cuser['uid'];
			$this->ismy = true;
		}else{
			if($this->sname){
				$user = $userapi->getUserByDomain($this->sname);
				$this->uid = $user['user_id'];
				$this->ismy = ($this->uid==$this->cuser['uid']);
			}else{
				$this->uid = $this->param('uid')?$this->param('uid'):$this->cuser['uid'];
				$this->ismy = ($this->uid==$this->cuser['uid']);
			}
		}
		return true;
	}

	private function userControl(){
		$userapi = load_api('user');
		$user = $userapi->getUserWithGroupByid($this->uid);
		$setting = load_api('setting')->getSetting('credit');
		$user['credits'] = array('name'=>lang('credits','view'),'value'=>$user['credits']);
		$user['credits1'] = array('name'=>$setting['ext_credits_1'],'value'=>$user['ext_credits_1']);
		$user['credits2'] = array('name'=>$setting['ext_credits_2'],'value'=>$user['ext_credits_2']);
		$user['credits3'] = array('name'=>$setting['ext_credits_3'],'value'=>$user['ext_credits_3']);
		if($user['is_star']){
			$user['star'] = load_db('star')->find_one(array('user_id'=>$this->uid));
		}
		$this->user = $user;
		$this->seo_title($user['nickname'].lang('ss','seo'),false);
		$this->relationView = $this->relationView($this->cuser['uid'], $this->uid);
		$this->activities = $this->userActivity($this->uid);
	}

	protected function userActivity($uid){
		$actdb = load_db('event/activity');
		$activities = $actdb->getActivityByUser($uid);
		foreach ($activities as $key=>$act){
			if($act['act_code']=='setavatar'){
				$activities[$key]['message'] = lang($act['act_code'],'view');
			}else if($act['act_code']=='postshare'){
				$activities[$key]['message'] = lang($act['act_code'],'view').' <a href="'.site_url('detail/index?shareid='.$act['rel_id']).'">'.$act['act_title'].'</a>';
			}else if($act['act_code']=='postvideo'){
				$activities[$key]['message'] = lang($act['act_code'],'view').' <a href="'.site_url('detail/index?shareid='.$act['rel_id']).'">'.$act['act_title'].'</a>';
			}else if($act['act_code']=='postcomment'){
				$activities[$key]['message'] = lang($act['act_code'],'view').' <a href="'.site_url('detail/index?shareid='.$act['rel_id']).'">'.$act['act_title'].'</a>';
			}else if($act['act_code']=='addlike'){
				$activities[$key]['message'] = lang($act['act_code'],'view').' <a href="'.site_url('detail/index?shareid='.$act['rel_id']).'">'.$act['act_title'].'</a>';
			}else if($act['act_code']=='follow'){
				$activities[$key]['message'] = lang($act['act_code'],'view').' <a href="'.site_url('detail/index?shareid='.$act['rel_id']).'">'.$act['act_title'].'</a>';
			}else if($act['act_code']=='addlikealbum'){
				$activities[$key]['message'] = lang($act['act_code'],'view').' <a href="'.site_url('detail/index?shareid='.$act['rel_id']).'">'.$act['act_title'].'</a>';
			}
		}
		return $activities;
	}

	public function output_pin(){
		$setting = load_api('setting')->getSetting('layoutpin');
		$pagesize = $setting['uipin_numperpage']?$setting['uipin_numperpage']:15;
		
		$numbershowpage = $setting['uipin_numbershowpage']?$setting['uipin_numbershowpage']:0;
		
		$args = array("page"=>"2");

		$page = $this->param('page','1');
		$wpage = $this->param('wpage');
		if($wpage&&$numbershowpage){
			$data['page'] = ($wpage-1)*$numbershowpage+$page;
			$args['wpage'] = $data['wpage'] = $wpage;
		}else{
			$data['page'] = $page;
		}
		$data['showpage'] = (($numbershowpage)&&($data['page']%$numbershowpage==0))?'1':'0';
		
		if($this->method=='focus'){
			$ptx_relationship = load_db("user/userrel");
			$followings_conditions['user_id'] = $this->uid;
			$args['uid']=$this->uid;
			$followings_sql = $ptx_relationship->findAllSql($followings_conditions,null," friend_id ");
			$conditions['id_sub']['user_id'] = array($followings_sql);
		}elseif($this->method=='share'||$this->method=='user'||$this->method=='domain'){
			$conditions['user_id'] = $args['uid'] = $this->uid;
		}elseif($this->method=='atshare'){
			$conditions['keyword'] = $args['keyword'] = 'atuser'.$this->uid;
		}
		if($this->sname){
			$args['sname']=$this->sname;
		}
		$shareapi = load_api('share');
		$shares = $shareapi->search($conditions,$data['page'],$pagesize,' ptx_share.create_time DESC ');
		if($shares){
			$this->nextpage_url = site_url_param('home/'.$this->method,$args);
			$pager = &load_class('Pager', 'core');
			unset($args['wf']);
			$this->pages = $pager->createPages('home/'.$this->method,$args);
			unset($args['page']);
			$data['wpages'] = $pager->createCustomPages('home/'.$this->method,$args,'wpage',$pagesize*$numbershowpage);
			$shares = $shareapi->prepareShares($shares);
			$this->tpl_waterfall = $this->render('waterfall/pin',array('shares'=>$shares,'showpage'=>$data['showpage']));
		}
		$this->pinsetting = $setting;
		$this->output("user/pin",$data,($this->page==1)?true:false);
	}

	public function focus(){
		if($this->page==1){
			$this->userControl();
		}
		$this->output_pin();
	}

	public function share(){
		if($this->page==1){
			$this->userControl();
		}
		$this->output_pin();
	}

	public function atshare(){
		if($this->page==1){
			$this->userControl();
		}
		$this->output_pin();
	}

	public function favshare(){
		if($this->page==1){
			$this->userControl();
		}
		$setting = load_api('setting')->getSetting('layoutpin');
		$pagesize = $setting['uipin_numperpage']?$setting['uipin_numperpage']:15;
		$args = array("page"=>"2");
		$conditions['user_id'] =$args['uid'] = $this->uid;
		if($this->sname){
			$args['sname']=$this->sname;
		}
		$shareapi = load_api('share');
		$favsharedb = load_db('share/favshare');
		$shares = $favsharedb->search($conditions,$this->page,$pagesize,null,' ptx_share.create_time DESC ');
		if($shares){
			$this->nextpage_url = site_url_param('home/favshare',$args);
			$pager = &load_class('Pager', 'core');
			$this->pages = $pager->createPages('home/favshare',$args);
			$shares = $shareapi->prepareShares($shares);
			$this->tpl_waterfall = $this->render('waterfall/pin',array('shares'=>$shares));
		}
		$this->pinsetting = $setting;
		$this->output("user/pin",array(),($this->page==1)?true:false);
	}

	public function albumshare(){
		$aid = $this->param('aid');
		$albumapi = load_api('album');
		if($album = $albumapi->findAlbumByid($aid)){
			$this->seo_title($album['nickname'].lang('ss','seo'),false);
			$this->seo_title($album['album_title']);
			$this->seo_keyword($album['album_title'].' '.$album['album_desc']);
			$this->seo_description($album['album_desc']);
			$data['ismy'] = ($album['user_id']==$this->cuser['uid']);
			$api = load_api('setting');
			$setting = $api->getSetting('layoutpin');
			$pagesize = $setting['uipin_numperpage']?$setting['uipin_numperpage']:15;
			$data['page'] = $this->param('page','1');

			if($data['page'] == 1){
				$data['liked'] = $albumapi->findFavAlbumByIds($aid,$this->cuser['uid']);
				$data['user'] = load_api('user')->getUserWithGroupByid($album['user_id']);
				$data['relationView'] = $this->relationView($this->cuser['uid'], $album['user_id']);
				$albumcomdb = load_db('comment/albumcomment');
				$comments = $albumcomdb->search(array('album_id'=>$aid),1,5);
				$pager = &load_class('Pager', 'core');
				$pdata = $pager->getPager();
				$data['total_comments'] = $pdata['total_count'];
				if($comments){
					foreach ($comments as $comment) {
						$comment['post_time_friend'] = pgmdate($comment['create_time']);
						$comment['user_avatar'] = useravatar($comment['user_id'], 'middle');
						$comment['comment_txt'] = load_api('puzzcode')->parse_message($comment['comment_txt'],null,true);
						$data['comments'][] = $comment;
					}
				}
			}

			$args = array("page"=>"2");
			$conditions['album_id'] = $args['aid'] = $aid;
			$data['album'] = $album;
			$data['nextpage_url'] = site_url_param('home/albumshare',$args);
			$shareapi = load_api('share');

			$shares = $shareapi->search($conditions,$data['page'],$pagesize,null);
			$shares = $shareapi->prepareShares($shares);
			if($setting['uipin_ads']){
				$shares = $shareapi->add_ads($shares);
			}
			$pager = &load_class('Pager', 'core');
			$data['pages'] = $pager->createPages('home/albumshare',$args);
			$data['tpl_waterfall'] = $this->render('waterfall/pin',array('shares'=>$shares));
			$data['pinsetting'] = $setting;
			$this->output("album/share",$data,($data['page'] == 1)?true:false);
		}
	}

	public function basicsetting(){
		$this->userControl();
		$this->output("user/basicsetting");
	}


	public function securitysetting(){
		$this->userControl();
		$this->output("user/securitysetting");
	}

	public function bindsetting(){
		$this->userControl();
		$connector = load_db('social/connector');
		$this->bind_connectors = $connector->get_bind_connectors($this->user['user_id']);
		$cs = array();
		foreach ($this->bind_connectors as $c){
			$vendor = $c['vendor'];
			$cs[$vendor]['id'] = $c['connect_id'];
			$cs[$vendor]['username'] = $c['username'];
		}
		$this->cs = $cs;
		$this->socialapis = load_api('setting')->getSetting('socialapi');
		$this->output("user/bindsetting");
	}

	public function album(){
		$settingapi = load_api('setting');
		$setting = $settingapi->getSetting('layoutalbum');

		$num_per_page = $setting['uialbum_numperpage']?$setting['uialbum_numperpage']:20;
		$numbershowpage = $setting['uialbum_numbershowpage']?$setting['uialbum_numbershowpage']:0;
		
		$page = $this->param('page','1');
		$wpage = $this->param('wpage');
		$args = array("page"=>"2","wf"=>"1");
		if($wpage&&$numbershowpage){
			$data['page'] = ($wpage-1)*$numbershowpage+$page;
			$args['wpage'] = $data['wpage'] = $wpage;
		}else{
			$data['page'] = $page;
		}
		$data['showpage'] = (($numbershowpage)&&($data['page']%$numbershowpage==0))?'1':'0';
		
		$this->userControl();
		if($this->uid){
			$conditions['user_id'] = $args['uid'] = $this->uid;
		}

		if($this->sname){
			$args['sname']=$this->sname;
		}
		$this->nextpage_url = site_url_param('home/album',$args);
		$api = load_api('album');
		$albums = $api->search($conditions,$data['page'],$num_per_page,'');
		$pager = &load_class('Pager', 'core');
		$this->pages = $pager->createPages('home/album',$args);
		unset($args['wf']);
		unset($args['page']);
		$data['wpages'] = $pager->createCustomPages('home/album',$args,'wpage',$num_per_page*$numbershowpage);
		foreach ($albums as $k=>$album){
			$albums[$k] = $api->prepareAlbum($album);
		}
		$this->tpl_waterfall = $this->render('waterfall/album',array('albums'=>$albums,'showpage'=>$data['showpage']));
		$this->albumsetting = $setting;
		//$this->seo_title($this->user['nickname'].lang('album_prefix'));
		//$this->seo_keyword($this->user['nickname'].lang('album_prefix'));
		//$this->seo_description($this->user['nickname'].lang('album_prefix'));
		$this->output("user/album",$data,($this->page==1)?true:false);
	}

	public function favalbum(){
		$settingapi = load_api('setting');
		$setting = $settingapi->getSetting('layoutalbum');

		$num_per_page = $setting['uialbum_numperpage']?$setting['uialbum_numperpage']:20;
		$this->page = $this->param('page','1');
		$args = array("page"=>"2","wf"=>"1");

		$this->userControl();
		$args = array("page"=>"2");
		if($this->uid){
			$conditions['user_id'] = $args['uid'] = $this->uid;
		}

		if($this->sname){
			$args['sname']=$this->sname;
		}
		$this->nextpage_url = site_url_param('home/favalbum',$args);
		$favalbum = load_db('album/favalbum');
		$albums = $favalbum->search($conditions,$this->page,$num_per_page);
		$pager = &load_class('Pager', 'core');
		$this->pages = $pager->createPages('home/favalbum',$args);
		$api = load_api('album');
		foreach ($albums as $k=>$album){
			$albums[$k] = $api->prepareAlbum($album);
		}
		$this->tpl_waterfall = $this->render('waterfall/album',array('albums'=>$albums));
		$this->albumsetting = $setting;
		//$this->seo_title($this->user['nickname'].lang('album_prefix'));
		//$this->seo_keyword($this->user['nickname'].lang('album_prefix'));
		//$this->seo_description($this->user['nickname'].lang('album_prefix'));
		$this->output("user/album",array(),($this->page==1)?true:false);
	}

	public function createalbum(){
		if($this->param("submit")){
			$count = load_api('album')->getalbumnumbyuid($this->cuser['uid']);
			if($count>=$this->memperm['maxalbum']&&!$this->isadmin&&!$this->iseditor){
				$this->ajax_failed_response(lang('reach_create_maxnum','tip').$this->memperm['maxalbum']);
				return;
			}
			if($data = $this->update_album_common()){
				$api = load_api('album');
				if($album = $api->addAlbum($data)){
					$album['url'] = site_url('home/albumshare?aid='.$album['album_id']);
					$this->ajax_success_response($album, lang('200_operatesuccess','tip'));
				}else{
					$this->ajax_failed_response(lang('500_operatefaild','tip'));
				}
			}
		}else {
			$this->categories = load_api('category')->getLastLevelCategories();
			$this->userControl();

			$this->shareSetting = load_api('setting')->getSetting('share');
			$this->output("user/createalbum");
		}
	}

	public function albumcheck($postdata, $param){
		return load_api('album')->albumcheck($postdata, $param);
	}

	public function update_album_common($act="update"){
		$album_title =  $this->param("album_title");
		$album_desc =  $this->param("album_desc");
		$category_id =  $this->param("category_id");
		$fvalidation = load_class('Form_validation');

		$shareSetting = $this->shareSetting;
		$minlenth=$shareSetting['album_range_s']?$shareSetting['album_range_s']:2;
		$maxlength=$shareSetting['album_range_l']?$shareSetting['album_range_l']:20;
		if($act=='update'){
			$fvalidation->set_rules('album_title', 'lang:album_title:field' , 'trim|required|min_length['.$minlenth.']|max_length['.$maxlength.']|xss_clean');
		}else{
			$fvalidation->set_rules('album_title', 'lang:album_title:field' , 'trim|required|min_length['.$minlenth.']|max_length['.$maxlength.']|xss_clean|callback_albumcheck');
		}
		$fvalidation->set_rules('album_desc', 'lang:album_desc:field' , 'trim|max_length[200]|xss_clean');
		$fvalidation->set_rules('category_id', 'lang:category_id:field' , 'trim|required');

		if ($fvalidation->run() == FALSE){
			$this->ajax_failed_response($fvalidation->error_string());
			return FALSE;
		}
		$data['album_title'] = $album_title;
		$data['album_desc'] = $album_desc;
		$data['category_id'] = $category_id;
		$data['user_id'] = $this->cuser['uid'];
		return $data;
	}

	public function albumupdate(){
		$album_id =  $this->param("aid");
		if(!$album_id){
			$this->ajax_failed_response(lang('lost_param','tip'));
			return;
		}
		$albumapi = load_api("album");
		if($this->album = $albumapi->findAlbumByid($album_id)){
			if($this->album['user_id']!=$this->cuser['uid']){
				$this->ajax_failed_response(lang('illegal_operation','tip'));
				return;
			}
		}else {
			$this->ajax_failed_response(lang('illegal_operation','tip'));
			return;
		}

		$act = $this->param("act");

		if($act=='edit'){
			if($data = $this->update_album_common()){
				if(load_db('album')->update(array('album_id'=>$album_id),$data)){
					$this->ajax_success_response(array('url'=>site_url('home/album')), lang('200_operatesuccess','tip'));
					return;
				}else{
					$this->ajax_failed_response(lang('500_operatefaild','tip'));
					return;
				}
			}
		}elseif($act=='delete'){
			if($albumapi->deletealbum($album_id)){
				$this->ajax_success_response(array('url'=>site_url('home/album')), lang('200_operatesuccess','tip'));
				return;
			}else{
				$this->ajax_failed_response(lang('500_operatefaild','tip'));
				return;
			}
		}else {
			$this->aid = $album_id;
			$this->categories = load_api('category')->getLastLevelCategories();
			$this->userControl();
			$this->output("user/albumupdate");
		}
	}

	public function timeline(){
		$this->resetPage = 0;
		$this->sharebuttons = load_api('setting')->getSetting('sharebutton');
		if($this->page==1){
			$this->userControl();
		}
		$num_per_page = 4;
		$args = array("page"=>2);
		if($this->uid){
			$conditions['user_id'] = $args['uid'] = $this->uid;
		}
		if($this->sname){
			$args['sname']=$this->sname;
		}
		$next_time = $this->param("next_time");
		$this->need_static = false;
		if($next_time){
			$now = $next_time;
		}else{
			$now = TIMESTAMP;
			$this->need_static = ($this->page==1)?true:false;
		}
		$ptx_share = load_db('share');
		$conditions['lt_time'] = $now;
		$last_share = $ptx_share->find_one($conditions," ptx_share.create_time DESC "," ptx_share.share_id,ptx_share.create_time ");
		$last_time = $last_share['create_time'];

		$last_post_month = (int)date('m',$last_time);
		$last_post_month_days = (int)date('t',$last_time);
		$last_post_year = (int)date('Y',$last_time);

		$this_month_time_first = mktime(0,0,0,$last_post_month,1,$last_post_year);
		$this_month_time_last = mktime(24,59,59,$last_post_month,$last_post_month_days,$last_post_year);
		$conditions['gt_time'] = $this_month_time_first;
		$conditions['lt_time'] = $this_month_time_last;

		$this_month_last_share = $ptx_share->find_one($conditions," ptx_share.create_time DESC "," ptx_share.share_id,ptx_share.create_time ");
		//$this_month_total = $ptx_share->count($conditions);

		$shares = $ptx_share->search($conditions,$this->page,$num_per_page,NULL," ptx_share.create_time DESC ");
		if(array_length($shares)==$num_per_page){
			$next_search_time = $shares[$num_per_page-1]['create_time'];
		}else{
			$next_search_time = $this_month_time_first;
			$this->resetPage = 1;
		}
		if($this_month_last_share['share_id']==$shares[0]['share_id']){
			if($this->isChineseVersion()){
				$this->timeline_date = $last_post_year.'年'.$last_post_month.'月';
			}else{
				$this->timeline_date = $last_post_year.'-'.$last_post_month;
			}
		}
		$shares = load_api('share')->prepareTimelineShares($shares);
		$args['next_time'] = $next_search_time;
		$this->nextpage_url = site_url_param('home/timeline',$args);
		$this->tpl_timeline = $this->render('timeline/pin',array('shares'=>$shares));
		/* $this->seo_title($this->user['nickname'].lang('timeline_prefix'));
		 $this->seo_keyword($this->user['nickname'].lang('timeline_prefix'));
		$this->seo_description($this->user['nickname'].lang('timeline_prefix')); */
		$this->output("user/timeline");
	}

	public function topics(){
		$this->page = $this->param('page','1');
		$this->userControl();

		$num_per_page = 5;
		$ptx_topic = load_db("topic");
		$category_id =  $this->param("cid");
		$args = array('uid'=>$this->uid);
		if($category_id){
			$conditions['category_id'] = $args['cid'] = $category_id;
		}
		$conditions['user_id'] = $this->uid;

		$topics = $ptx_topic->search($conditions,$this->page,$num_per_page);
		$pager = &load_class('Pager', 'core');
		$this->pages = $pager->createPages('home/topics',$args);
		$shareapi = load_api('share');
		foreach ($topics as $key=>$topic){
			$share_conditions['keyword'] = 'topic'.pzxencode($topic['topic_title']).'t';
			$share_conditions['type'] = 'noarticle';
			$shares = $shareapi->search($share_conditions,1,7,null);
			$topics[$key]['shares'] = $shareapi->prepareShares($shares);
			$pageData = $pager->getPager();
			$topics[$key]['numbershares'] = $pageData['total_count'];
			$topics[$key]['isowner'] = ($topic['user_id']==$this->cuser['uid']);
			$topics[$key]['keywords'] = ($topic['keyword'])?encodekeywordsarray(explode(',', $topic['keyword'])):null;
		}
		$this->topics = $topics;
		$this->output("user/topics");
	}

	public function groups(){
		$this->uid = $this->cuser['uid'];
		$this->ismy = true;
		$this->page = $this->param('page','1');
		$this->userControl($this->uid);

		$num_per_page = 10;
		$ptx_group = load_db("group");
		$category_id =  $this->param("cid");
		$args = array('uid'=>$this->uid);
		if($category_id){
			$conditions['category_id'] = $args['cid'] = $category_id;
		}

		$conditions['user_id'] = $this->uid;

		$groups = $ptx_group->search($conditions,$this->page,$num_per_page);
		$pager = &load_class('Pager', 'core');
		$this->pages = $pager->createPages('home/groups',$args);
		$ptx_share = load_db('share');
		foreach ($groups as $key=>$group){
			$share_conditions['keyword'] = 'group'.$group['group_id'].'g';
			$shares = $ptx_share->count($share_conditions);
			$groups[$key]['total_share'] = $shares;
			$groups[$key]['isowner'] = ($group['user_id']==$this->cuser['uid']);
		}

		$this->groups = $groups;
		$this->output("user/groups");
	}

	public function favtopic(){
		$this->page = $this->param('page','1');
		$this->userControl();

		$num_per_page = 5;
		$favtopicdb = load_db("topic/favtopic");
		$args = array('uid'=>$this->uid);
		$conditions['user_id'] = $this->uid;

		$topics = $favtopicdb->search($conditions,$this->page,$num_per_page);
		$pager = &load_class('Pager', 'core');
		$this->pages = $pager->createPages('home/favtopic',$args);
		$shareapi = load_api('share');
		foreach ($topics as $key=>$topic){
			$share_conditions['keyword'] = 'topic'.pzxencode($topic['topic_title']).'t';
			$share_conditions['type'] = 'noarticle';
			$shares = $shareapi->search($share_conditions,1,9,null);
			$topics[$key]['shares'] = $shareapi->prepareShares($shares);
			$pageData = $pager->getPager();
			$topics[$key]['numbershares'] = $pageData['total_count'];
			$topics[$key]['keywords'] = ($topic['keyword'])?encodekeywordsarray(explode(',', $topic['keyword'])):null;
		}
		$this->topics = $topics;
		$this->output("user/topics");
	}

	public function createtopic(){
		if($this->param("submit")){
			$count = load_api('topic')->gettopicnumbyuid($this->cuser['uid']);
			if($count>=$this->memperm['maxcrtopic']&&!$this->isadmin&&!$this->iseditor){
				$this->ajax_failed_response(lang('reach_create_maxnum','tip').$this->memperm['maxcrtopic']);
				return;
			}
				
			if($data = $this->update_topic_common()){
				if($topicid = load_db("topic")->add_one($data)){
					$cover = $this->param('cover');
					if($cover&&filename_check($cover)){
						$cover = BASEPATH.$cover;
						if(file_exists($cover)){
							$banner_info = banner_path($topicid);
							$banner_dir = BASEPATH.$banner_info['dir'];
							(!is_dir($banner_dir))&&@mkdir($banner_dir,0777,true);
							file_exists($banner_dir.$banner_info['filename']) && unlink($banner_dir.$banner_info['filename']);
							@copy($cover, $banner_dir.$banner_info['filename']);
							$imagelib = &load_class('ImageLib');
							$imagelib->crop_square_size($banner_dir.$banner_info['filename'],430,200);
							$imagelib->crop_square_size($banner_dir.$banner_info['filename'],220,240,'cover');
						}
					}
					$this->ajax_success_response(array('url'=>site_url('home/topics')), lang('200_operatesuccess','tip'));
					return;
				}
			}
			$this->ajax_failed_response(lang('500_operatefaild','tip'));
			return;
		}else {
			$this->userControl();
			$this->output("user/createtopic");
		}
	}

	public function createstore(){
		if($this->param("submit")){
			$params=array('category_id'=>'','store_name'=>'0','province'=>'','city'=>'','address'=>'','phone1'=>'','phone2'=>'','phone3'=>'','keyword'=>'','store_desc'=>'');
			foreach ($params as $key=>$default){
				$data[$key] = $this->param($key,$default);
			}
			$data['poster_id'] = $this->cuser['uid'];
			$data['poster_nickname'] = $this->cuser['nickname'];
			if($data['keyword']){
				$data['keyword'] = $data['keyword'];
				$data['keyword_search'] = encodekeywords(explode(',', $data['keyword']));
			}
			if($storeid = load_db('store')->add_one($data)){
				$cover = $this->param('cover');
				if($this->param('bannerchanged')=='true'&&$cover&&filename_check($cover)){
					$cover = BASEPATH.$cover;
					if(file_exists($cover)){
						$res = load_api('store')->storeres($storeid);
						$dirpath = BASEPATH.$res['dir'];
						(!is_dir($dirpath))&&@mkdir($dirpath,0777,true);
						file_exists($dirpath.$res['avatar']) && unlink($dirpath.$res['avatar']);
						@copy($cover, $dirpath.$res['avatar']);
					}
				}
				$applydb = load_db('misc/apply');
				if(!$applydb->find_one(array('user_id'=>$this->cuser['uid'],'rel_id'=>$storeid))){
					$applydb->add_storeapply($this->cuser['uid'],$data['category_id'],$storeid,$data['store_desc']);
				}
				$this->ajax_success_response(array('url'=>site_url('store/review?storeid='.$storeid)), lang('200_operatesuccess','tip'));
				return;
			}
			$this->ajax_failed_response(lang('500_operatefaild','tip'));
			return;
		}else {
			$this->userControl();
			$this->output("user/createtopic");
		}
	}

	public function creategroup(){
		if($this->param("submit")){
			$count = load_api('group')->getgroupnumbyuid($this->cuser['uid']);
			if($count>=$this->memperm['maxcrgroup']&&!$this->isadmin&&!$this->iseditor){
				$this->ajax_failed_response(lang('reach_create_maxnum','tip').$this->memperm['maxcrgroup']);
				return;
			}
			if($data = $this->update_group_common()){
				if($gid = load_db("group")->add_one($data)){
					$ugdata['user_id'] = $this->cuser['uid'];
					$ugdata['group_id'] = $gid;
					$ugdata['is_admin'] = 1;
					load_db("group/ugroup")->add_one($ugdata);

					$cover = $this->param('cover');
					if($cover&&filename_check($cover)){
						$cover = BASEPATH.$cover;
						if(file_exists($cover)){
							$banner_info = banner_path($gid,'group');
							$banner_dir = BASEPATH.$banner_info['dir'];
							(!is_dir($banner_dir))&&@mkdir($banner_dir,0777,true);
							file_exists($banner_dir.$banner_info['filename']) && unlink($banner_dir.$banner_info['filename']);
							@copy($cover, $banner_dir.$banner_info['filename']);
						}
					}

					$this->ajax_success_response(array('url'=>site_url('home/groups')), lang('200_operatesuccess','tip'));
					return;
				}
			}
			$this->ajax_failed_response(lang('500_operatefaild','tip'));
			return;
		}else {
			$this->userControl();
			$this->output("user/creategroup");
		}
	}

	public function updatetopic(){
		if($topicid = $this->param("topicid")){
			$this->topic = load_db("topic")->find_one(array('topic_id'=>$topicid));
		}

		if(!$this->topic){
			$this->redirect(site_url('home/topics'), lang('404_error_content','tip'));
			return;
		}
		if($this->topic['user_id']!=$this->cuser['uid']){
			$this->redirect(site_url('home/topics'), lang('illegal_operation','tip'));
			return;
		}

		if($this->param("submit")){
			if($data = $this->update_topic_common()){
				if(load_db("topic")->update(array('topic_id'=>$topicid),$data)){
					$cover = $this->param('cover');
					if($this->param('bannerchanged')=='true'&&$cover&&filename_check($cover)){
						$cover = BASEPATH.$cover;
						if(file_exists($cover)){
							$banner_info = banner_path($topicid);
							$banner_dir = BASEPATH.$banner_info['dir'];
							(!is_dir($banner_dir))&&@mkdir($banner_dir,0777,true);
							file_exists($banner_dir.$banner_info['filename']) && unlink($banner_dir.$banner_info['filename']);
							@copy($cover, $banner_dir.$banner_info['filename']);

							$imagelib = &load_class('ImageLib');
							$imagelib->crop_square_size($banner_dir.$banner_info['filename'],430,200);
							$imagelib->crop_square_size($banner_dir.$banner_info['filename'],220,240,'cover');
						}
					}

					$this->ajax_success_response(array('url'=>site_url('home/topics')), lang('200_operatesuccess','tip'));
					return;
				}
			}
			$this->ajax_failed_response(lang('500_operatefaild','tip'));
			return;
		}else {
			$this->userControl(d);
			$this->output("user/updatetopic");
		}
	}

	public function updategroup(){
		if($groupid = $this->param("groupid")){
			$this->group = load_db("group/ugroup")->find_one(array('user_id'=>$this->cuser['uid'],'group_id'=>$groupid)," pgroup.*,ptx_user_group.is_admin ");
		}

		if(!$this->group){
			$this->redirect(site_url('home/groups'), lang('404_error_content','tip'));
			return;
		}
		if(!$this->group['is_admin']){
			$this->redirect(site_url('home/groups'), lang('illegal_operation','tip'));
			return;
		}

		if($this->param("submit")){
			if($data = $this->update_group_common()){
				if(load_db("group")->update(array('group_id'=>$groupid),$data)){
					$cover = $this->param('cover');
					if($this->param('bannerchanged')=='true'&&$cover&&filename_check($cover)){
						$cover = BASEPATH.$cover;
						if(file_exists($cover)){
							$banner_info = banner_path($groupid,'group');
							$banner_dir = BASEPATH.$banner_info['dir'];
							(!is_dir($banner_dir))&&@mkdir($banner_dir,0777,true);
							file_exists($banner_dir.$banner_info['filename']) && unlink($banner_dir.$banner_info['filename']);
							@copy($cover, $banner_dir.$banner_info['filename']);
						}
					}
					$this->ajax_success_response(array('url'=>site_url('home/groups')), lang('200_operatesuccess','tip'));
					return;
				}
			}
			$this->ajax_failed_response(lang('500_operatefaild','tip'));
			return;

		}else {
			$this->userControl();
			$this->output("user/updategroup");
		}
	}

	private function update_topic_common(){
		$topic_title =  $this->param("topic_title");
		$topic_desc =  $this->param("topic_desc");
		$category_id =  $this->param("category_id");
		$keyword =  $this->param("keyword");

		if(!$topic_title||!$category_id){
			$this->ajax_failed_response(lang('lost_param',tip));
			return false;
		}
		$data['topic_title'] = $topic_title;
		$data['topic_desc'] = $topic_desc;
		$data['category_id'] = $category_id;
		if($keyword){
			$data['keyword'] = $keyword;
			$data['keyword_search'] = encodekeywords(explode(',', $keyword));
		}
		$data['user_id'] = $this->cuser['uid'];
		return $data;
	}

	private function update_group_common(){
		$group_title =  $this->param("group_title");
		$group_desc =  $this->param("group_desc");
		$category_id =  $this->param("category_id");
		$keyword =  $this->param("keyword");

		if(!$group_title||!$category_id){
			$this->ajax_failed_response(lang('lost_param',tip));
			return false;
		}
		$data['group_title'] = $group_title;
		$data['group_desc'] = $group_desc;
		$data['category_id'] = $category_id;
		if($keyword){
			$data['keyword'] = $keyword;
			$data['keyword_search'] = encodekeywords(explode(',', $keyword));
		}
		$data['user_id'] = $this->cuser['uid'];
		return $data;
	}

	public function starsetting(){
		if($this->param("submit")){
			if($data = $this->update_group_common()){
				if($gid = load_db("group")->add_one($data)){
					$ugdata['user_id'] = $this->cuser['uid'];
					$ugdata['group_id'] = $gid;
					$ugdata['is_admin'] = 1;
					load_db("group/ugroup")->add_one($ugdata);

					$cover = $this->param('cover');
					if($cover&&filename_check($cover)){
						$cover = BASEPATH.$cover;
						if(file_exists($cover)){
							$banner_info = banner_path($gid,'group');
							$banner_dir = BASEPATH.$banner_info['dir'];
							(!is_dir($banner_dir))&&@mkdir($banner_dir,0777,true);
							file_exists($banner_dir.$banner_info['filename']) && unlink($banner_dir.$banner_info['filename']);
							@copy($cover, $banner_dir.$banner_info['filename']);
						}
					}

					$this->ajax_success_response(array('url'=>site_url('home/groups')), lang('200_operatesuccess','tip'));
					return;
				}
			}
			$this->ajax_failed_response(lang('500_operatefaild','tip'));
			return;
		}else {
			$this->uid = $this->cuser['uid'];
			$this->ismy = true;
			$this->userControl($this->uid);
			$this->output("user/starsetting");
		}
	}

	public function store(){
		$this->userControl();
		$act =$this->act = $this->param('act');
		if($act=='create'){
			$this->output("user/createstore");
			return;
		}elseif ($act=='submit'){
			if($storeid =  $this->param("storeid")){
				$this->store = load_api("store")->getStoreById($storeid);
			}
			if(!$this->store){
				$this->redirect(site_url('home/store'), lang('404_error_content','tip'));
				return;
			}
			$params=array('category_id'=>'','store_name'=>'0','province'=>'','city'=>'','address'=>'','phone1'=>'','store_desc'=>'');
			foreach ($params as $key=>$default){
				$data[$key] = $this->param($key,$default);
			}
			$sg = &load_class('Segment');
			$sgresult = $sg->getDbData($data['store_name']);
			$data['keyword'] = $sg['keyword'];
			$data['keywordSearch'] = $sg['keywordSearch'];
			load_db('store')->updateStoreByid($storeid,$data);
			$this->ajax_success_response(array('url'=>site_url('home/groups')), lang('200_operatesuccess','tip'));
			return;
		}elseif($act=='fav'){
			$this->page = $this->param('page','1');
			$num_per_page = 10;
			$favstoredb = load_db("store/favstore");
			$args = array('uid'=>$this->uid);
			$conditions['user_id'] = $this->uid;

			$stores = $favstoredb->search($conditions,$this->page,$num_per_page);
			$pager = &load_class('Pager', 'core');
			$this->pages = $pager->createPages('home/store?act=fav',$args);
			foreach ($stores as $key=>$store){
				$stores[$key]['liked'] = true;
			}
			$this->stores = load_api('store')->preparestores($stores);
			$this->output("user/stores");
		}elseif($act=='share'){
			$this->page = $this->param('page','1');
			$num_per_page = 10;
			$storedb = load_db("store");
			$args = array('uid'=>$this->uid);
			$conditions['poster_id'] = $this->uid;
			$stores = $storedb->search($conditions,$this->page,$num_per_page);
			$pager = &load_class('Pager', 'core');
			$this->pages = $pager->createPages('home/store',$args);
			$this->stores = load_api('store')->preparestores($stores);
			$this->output("user/stores");
		}elseif($act=='approved'){
			$this->page = $this->param('page','1');
			$num_per_page = 10;
			$storedb = load_db("store");
			$args = array('uid'=>$this->uid);
			$conditions['user_id'] = $this->uid;
			$stores = $storedb->search($conditions,$this->page,$num_per_page);
			$pager = &load_class('Pager', 'core');
			$this->pages = $pager->createPages('home/store',$args);
			$this->stores = load_api('store')->preparestores($stores);
			$this->output("user/stores");
		}elseif($act=='delete'){
			if($storeid =  $this->param("storeid")){
				$this->store = load_api("store")->getStoreById($storeid);
			}
			if(!$this->store){
				$this->redirect(site_url('home/store'), lang('404_error_content','tip'));
				return;
			}
			if($this->isadmin||$this->iseditor||$this->store['user_id']==$this->cuser['uid']){
				load_api('store')->delete($storeid);
				$this->redirect(site_url('home/store'), lang('200_deletesuccess','tip'));
			}
		}else{
			$this->page = $this->param('page','1');
			$num_per_page = 10;
			$storedb = load_db("store");
			$args = array('uid'=>$this->uid);
			$conditions['poster_id'] = $this->uid;

			$stores = $storedb->search($conditions,$this->page,$num_per_page);
			$pager = &load_class('Pager', 'core');
			$this->pages = $pager->createPages('home/store',$args);
			$this->stores = $stores;
			$this->output("user/stores");
		}
	}

	public function message(){
		$this->uid = $this->cuser['uid'];
		$this->ismy = true;
		$this->userControl($this->uid);
		$this->page = $this->param('page','1');
		$num_per_page = 10;
		$db = load_db('message');
		$conditions = ' ptx_message.to_user_id=\''.$this->cuser['uid'].'\' OR ptx_message.from_user_id=\''.$this->cuser['uid'].'\' ';
		$this->messages = $db->search($conditions,$this->page,$num_per_page);
		$pager = &load_class('Pager', 'core');
		$this->pages = $pager->createPages('home/message',array());

		if($this->page==1){
			$conditions_update['to_user_id']=$this->cuser['uid'];
			$conditions_update['is_read']='0';
			$db->update($conditions_update,array('is_read'=>1));
			$db->clean_message_num($this->cuser['uid'],$this->memperm['maxmessage']?$this->memperm['maxmessage']:10);
		}
		$this->output("user/message");

	}

	public function alert(){
		$this->userControl();
		$this->page = $this->param('page','1');
		$num_per_page = 10;
		$db = load_db('event/activity');
		$this->messages = $db->search(array('to_user_id'=>$this->cuser['uid']),$this->page,$num_per_page);
		$pager = &load_class('Pager', 'core');
		$this->pages = $pager->createPages('home/alert',array());

		if($this->page==1){
			$conditions_update['to_user_id']=$this->cuser['uid'];
			$conditions_update['is_read']='0';
			$db->update($conditions_update,array('is_read'=>1));
		}
		$this->output("user/messagealert");

	}

	public function sendmessage(){
		if(!$this->sysperm['allowmessage']){
			$this->ajax_failed_response(lang('nopermission','tip'));
			return;
		}
		$message_user =  $this->param("message_user");
		$message_content =  $this->param("message_content");

		if($user=load_api('user')->getUserByNick($message_user)){
			$data['from_user_id'] = $this->cuser['uid'];
			$data['to_user_id'] = $user['user_id'];
			$data['message_txt'] = $message_content;

			load_db('message')->add_one($data);
			$this->ajax_success_response(null,lang('200_postsuccess','tip'));
			return;
		}
		$this->ajax_failed_response(lang('500_postfaild','tip'));
		return;
	}

	public function user(){
		$this->share();
	}

	public function domain(){
		$this->share();
	}

	public function following(){
		$settingapi = load_api('setting');
		$setting = $settingapi->getSetting('layoutalbum');
		$num_per_page = $setting['uialbum_numperpage']?$setting['uialbum_numperpage']:20;
		$numbershowpage = $setting['uialbum_numbershowpage']?$setting['uialbum_numbershowpage']:0;
		
		$page = $this->param('page','1');
		$wpage = $this->param('wpage');
		$args = array("page"=>"2","wf"=>"1");
		if($wpage&&$numbershowpage){
			$data['page'] = ($wpage-1)*$numbershowpage+$page;
			$args['wpage'] = $data['wpage'] = $wpage;
		}else{
			$data['page'] = $page;
		}
		$data['showpage'] = (($numbershowpage)&&($data['page']%$numbershowpage==0))?'1':'0';
		if($data['page']==1){
			$this->userControl();
		}
		if(is_numeric($this->uid)){
			$conditions['user_id'] = $args['uid'] = $this->uid;
		}else{
			$this->redirect(site_url(config_item('default_module')), lang('illegal_operation','tip'));
			return;
		}
		if($this->sname){
			$args['sname']=$this->sname;
		}
		$followings = load_db('user/userrel')->search($conditions,$data['page'],$num_per_page," friend.* ");
		$followings = $this->fillUserWithShare($followings);
		$user_id = $this->islogin?$this->cuser['uid']:0;
		$followings = $this->addrelation($followings,$user_id);
		$pager = &load_class('Pager', 'core');
		$this->pages = $pager->createPages('home/following',$args);
		$this->nextpage_url = site_url_param('home/following',$args);
		unset($args['wf']);
		unset($args['page']);
		$data['wpages'] = $pager->createCustomPages('home/fans',$args,'wpage',$num_per_page*$numbershowpage);
		//$this->seo_title($this->user['nickname'].T('following_prefix'));
		//$this->seo_keyword($this->user['nickname'].T('following_prefix'));
		//$this->seo_description($this->user['nickname'].T('following_prefix'));
		$this->tpl_waterfall = $this->render('waterfall/user',array('users'=>$followings,'showpage'=>$data['showpage']));
		$this->layoutsetting = $setting;
		$this->output("user/friends",$data,($this->page==1)?true:false);
	}

	private function fillUserWithShare($users){
		$ptx_share = load_db('share');
		$shareapi = load_api('share');
		foreach ($users as $key=>$user) {
			$s= $ptx_share->find_one(array('user_id'=>$user['user_id']));
			if($s) $users[$key]['share'] = $shareapi->prepareshare($s);
		}
		return $users;
	}

	private function addrelation($friends,$user_id){
		foreach ($friends as $key=>$friend){
			$friends[$key]['relation_view'] = $this->relationView($user_id,$friend['user_id']);
		}
		return $friends;
	}

	public function fans(){
		$settingapi = load_api('setting');
		$setting = $settingapi->getSetting('layoutalbum');
		$num_per_page = $setting['uialbum_numperpage']?$setting['uialbum_numperpage']:20;
		$numbershowpage = $setting['uialbum_numbershowpage']?$setting['uialbum_numbershowpage']:0;
		
		$page = $this->param('page','1');
		$wpage = $this->param('wpage');
		$args = array("page"=>"2","wf"=>"1");
		if($wpage&&$numbershowpage){
			$data['page'] = ($wpage-1)*$numbershowpage+$page;
			$args['wpage'] = $data['wpage'] = $wpage;
		}else{
			$data['page'] = $page;
		}
		$data['showpage'] = (($numbershowpage)&&($data['page']%$numbershowpage==0))?'1':'0';
		
		if($data['page']==1){
			$this->userControl();
		}
		if(is_numeric($this->uid)){
			$conditions['friend_id'] = $args['uid'] = $this->uid;
		}else{
			$this->redirect(site_url(config_item('default_module')), lang('illegal_operation','tip'));
			return;
		}
		if($this->sname){
			$args['sname']=$this->sname;
		}
		$followings = load_db('user/userrel')->search($conditions,$data['page'],$num_per_page," user.* ");
		$followings = $this->fillUserWithShare($followings);
		$user_id = $this->islogin?$this->cuser['uid']:0;
		$followings = $this->addrelation($followings,$user_id);
		$pager = &load_class('Pager', 'core');
		$this->pages = $pager->createPages('home/fans',$args);
		$this->nextpage_url = site_url_param('home/fans',$args);
		unset($args['wf']);
		unset($args['page']);
		$data['wpages'] = $pager->createCustomPages('home/fans',$args,'wpage',$num_per_page*$numbershowpage);
		//$this->seo_title($this->user['nickname'].T('following_prefix'));
		//$this->seo_keyword($this->user['nickname'].T('following_prefix'));
		//$this->seo_description($this->user['nickname'].T('following_prefix'));
		$this->tpl_waterfall = $this->render('waterfall/user',array('users'=>$followings,'showpage'=>$data['showpage']));
		$this->layoutsetting = $setting;
		$this->output("user/friends",$data,($this->page==1)?true:false);
	}
}



